import * as PIXI from 'pixi.js'
import { createSprite } from '@renderer/utils/bundle'
import { diyCategoryClick } from '@renderer/utils/events'
import { getPixiData, setPixi, setPixiData } from '@renderer/store/modules/usePixiStore'
import { CATEGORY } from '@renderer/config'
import param, { leftHeightUsage, leftWidthUsage, setCategoryKey } from '../param'
import useDiyStore from '@renderer/store/modules/useDiyStore'

export default async (): Promise<PIXI.Container<PIXI.ContainerChild>> => {
  const diyStore = useDiyStore()
  const categoryContainer = new PIXI.Container()
  await Promise.all(
    // 遍历种类对应的类别组
    Object.entries(CATEGORY).map(async ([typeKey, categorys]) => {
      const typeContainerData = getPixiData(param.value.typeKey[typeKey]) // 类型的数据
      const typeContainer = new PIXI.Container() // 每组类别存放到一个容器中
      await Promise.all(
        Object.entries(categorys).map(async ([key, value], index) => {
          const container = new PIXI.Container()
          const unselection = await createSprite('unselectionType')
          const selection = await createSprite('selectionType')
          container.addChild(unselection)
          container.addChild(selection)
          selection.visible = diyStore.creationData.category === key
          const text = new PIXI.Text({
            text: key.substring(0, 2),
            style: {
              fontFamily: 'XQFont',
              fontSize: param.value.fontSize,
              fill: param.value.fill,
              align: 'center',
            },
          })
          text.anchor.set(0.5)
          text.position.set(container.width / 2 + 20, container.height / 2 - 3)
          container.addChild(text)
          container.position.set((index % 5) * container.width * 1.1, Math.floor(index / 5) * container.height * 1.1)
          setPixi(container.uid, container)
          setPixiData(container.uid, {
            key,
            value,
          })
          setCategoryKey(key, container)
          diyCategoryClick.whiteAdd(container)
          typeContainer.addChild(container)
        }),
      )
      typeContainer.visible = diyStore.creationData.type === typeKey
      typeContainerData.category = typeContainer.uid // 将类型与其下级的类别关联起来
      categoryContainer.addChild(typeContainer)
      setPixi(typeContainer.uid, typeContainer)
      setPixiData(typeContainer.uid, {
        key: typeKey,
      })
    }),
  )
  categoryContainer.position.set(0, param.value.startHeight + param.value.leftUsageHeight)
  leftWidthUsage(categoryContainer)
  leftHeightUsage(categoryContainer)
  return categoryContainer
}
